/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.farent.solutions.plugins.stripes.hyperstripes.core;

import java.util.List;

/**
 *
 * @author user
 */
public class ComponentTypeStateHelperFactory {

    static {
        ComponentAnnotationProcessor.getInstance().startUp();
    }

    public ComponentTypeStateHelper getStatesHandlerForComponent( Class tagName,
            StripesApplicationContext applicationContext )
    {
        ComponentTypeStateHelper provider = null;
        List<Class> classesWithAnnotation =
                ComponentAnnotationProcessor.getInstance().
                getClassesWithAnnotation( StateHelperProvider.class );
        for ( Class classWithAnnotation : classesWithAnnotation )
        {
            StateHelperProvider annotation = ( StateHelperProvider ) classWithAnnotation.getAnnotation(
                    StateHelperProvider.class );
            if( tagName.getClass().equals(annotation.value()) )
            {
                try
                {
                    provider = ( ComponentTypeStateHelper ) classWithAnnotation.newInstance();
                }
                catch ( InstantiationException ex )
                {
                    throw new RuntimeException( ex );
                }
                catch ( IllegalAccessException ex )
                {
                    throw new RuntimeException( ex );
                }
            }
        }
        if( provider == null  )
        {
            provider = new DefaultComponentTypeStateHelper();
        }
        provider.setHsContext(applicationContext);

        return provider;
    }

    private ComponentTypeStateHelperFactory() {
    }

    public static ComponentTypeStateHelperFactory getInstance() {
        return ComponentTypeStateHelperFactoryHolder.INSTANCE;
    }

    private static class ComponentTypeStateHelperFactoryHolder {

        private static final ComponentTypeStateHelperFactory INSTANCE = new ComponentTypeStateHelperFactory();
    }
}
